#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <sys/stat.h>

int compare_folders(const char *dir1, const char *dir2);

int main() {
    int result = compare_folders("folder1", "folder2");
    if (result) {
        printf("The folders are different\n");
    } else {
        printf("The folders are the same\n");
    }

    return 0;
}

int compare_folders(const char *dir1, const char *dir2) {
    DIR *dp1, *dp2;
    struct dirent *entry1, *entry2;
    struct stat statbuf1, statbuf2;

    // 打开文件夹
    dp1 = opendir(dir1);
    dp2 = opendir(dir2);
    if (dp1 == NULL || dp2 == NULL) {
        printf("Cannot open directory\n");
        return -1;
    }

    // 比较文件名和子目录名
    while ((entry1 = readdir(dp1)) != NULL && (entry2 = readdir(dp2)) != NULL) {
        if (strcmp(entry1->d_name, ".") == 0 || strcmp(entry1->d_name, "..") == 0) {
            continue;
        }

        if (strcmp(entry1->d_name, entry2->d_name) != 0) {
            closedir(dp1);
            closedir(dp2);
            return -1;
        }
    }

    // 检查文件和子目录数量是否相同
    if ((entry1 = readdir(dp1)) != NULL || (entry2 = readdir(dp2)) != NULL) {
        closedir(dp1);
        closedir(dp2);
        return -1;
    }

    // 比较每个子目录
    rewinddir(dp1);
    rewinddir(dp2);
    while ((entry1 = readdir(dp1)) != NULL) {
        if (strcmp(entry1->d_name, ".") == 0 || strcmp(entry1->d_name, "..") == 0) {
            continue;
        }

        char subdir1[100] = "";
        strcat(subdir1, dir1);
        strcat(subdir1, "/");
        strcat(subdir1, entry1->d_name);

        char subdir2[100] = "";
        strcat(subdir2, dir2);
        strcat(subdir2, "/");
        strcat(subdir2, entry1->d_name);

        stat(subdir1, &statbuf1);
        stat(subdir2, &statbuf2);

        if (S_ISDIR(statbuf1.st_mode)) {
            if (compare_folders(subdir1, subdir2) != 0) {
                closedir(dp1);
                closedir(dp2);
                return -1;
            }
        } else {
            FILE *fp1 = fopen(subdir1, "rb");
            FILE *fp2 = fopen(subdir2, "rb");
            if (fp1 == NULL || fp2 == NULL) {
                printf("Cannot open file\n");
                return -1;
            }

            int ch1, ch2;
            do {
                ch1 = fgetc(fp1);
                ch2 = fgetc(fp2);
                if (ch1 != ch2) {
                    fclose(fp1);
                    fclose(fp2);
                    closedir(dp1);
                    closedir(dp2);
                    return -1;
                }
            } while (ch1 != EOF && ch2 != EOF);

            fclose(fp1);
            fclose(fp2);
        }
    }

    // 关闭文件夹
    closedir(dp1);
    closedir(dp2);

    return 0;
}